'use strict';

angular.module('myApp.user_edit', []).controller('user_editCtrl',['$scope','$routeParams','$http','$location',function($scope,$routeParams,$http,$location){

    $scope.passwordEdit = false;

    $http.get('v1/admin/'+$routeParams.id).success(function(data){
		if(!data.error){
			$scope.user = data.result[0];
			$scope.user.password = "";
			$http.get('v1/role').success(function(data){
				if(!data.error){
					for (var i = data.result.length - 1; i >= 0; i--) {
						if($scope.user.role_id.indexOf(data.result[i].id)>-1)
							data.result[i].checked = true;
					};
					$scope.roles = data.result;
				}  
		    });
		    
		}  
    });

    $scope.submit = function(){
    	var role_id = [];
    	for (var i = $scope.roles.length - 1; i >= 0; i--) {
    		if($scope.roles[i].checked == true){
    			role_id.push($scope.roles[i].id);
    		}
    	}
    	var put_data ={role_id:role_id};

    	if($scope.passwordEdit == true && $scope.user.password.length <6){
	    	
	    	alert("密码过短！");return false;	
    	}else{
    		put_data['password'] = $scope.user.password; 	
    	}

    	$http.put('v1/admin/'+$routeParams.id,put_data).success(function(data){
    		if(!data.error){
    			alert(data.message,"success");
    		}else{
    			alert(data.message);
    		}
    	});

    	
    };

}]);
